from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn

INPUT_DOCX = '代码导出结果_无空行.docx'  # 可修改为你的输入文件
OUTPUT_DOCX = '代码导出结果_无空行_去除最后一页.docx'

doc = Document(INPUT_DOCX)
new_doc = Document()

# 按分页符分组所有段落
pages = []
current_page = []
for para in doc.paragraphs:
    # 检查是否为分页符段落
    is_page_break = False
    for run in para.runs:
        for br in run._element.findall('.//w:br', namespaces=run._element.nsmap):
            if br.get(qn('w:type')) == 'page':
                is_page_break = True
                break
        if is_page_break:
            break
    if is_page_break:
        pages.append(current_page)
        current_page = []
    else:
        current_page.append(para)
if current_page:
    pages.append(current_page)

# 移除最后一页
if len(pages) > 1:
    pages = pages[:-1]
else:
    print("警告：文档只有一页，无法删除最后一页！")

# 写入新文档
for idx, page in enumerate(pages):
    for para in page:
        new_para = new_doc.add_paragraph()
        for run in para.runs:
            new_run = new_para.add_run(run.text)
            new_run.bold = run.bold
            new_run.italic = run.italic
            new_run.underline = run.underline
            new_run.font.size = run.font.size
            new_run.font.name = run.font.name
    if idx != len(pages) - 1:
        new_doc.add_page_break()

# 添加居中页脚页码
section = new_doc.sections[0]
footer = section.footer
footer_p = footer.paragraphs[0]
footer_p.alignment = 1  # 居中

fldChar1 = OxmlElement('w:fldChar')
fldChar1.set(qn('w:fldCharType'), 'begin')

instrText = OxmlElement('w:instrText')
instrText.set(qn('xml:space'), 'preserve')
instrText.text = ' PAGE '

fldChar2 = OxmlElement('w:fldChar')
fldChar2.set(qn('w:fldCharType'), 'end')

footer_run = footer_p.add_run()
footer_run._r.append(fldChar1)
footer_run._r.append(instrText)
footer_run._r.append(fldChar2)

new_doc.save(OUTPUT_DOCX)
print(f'已生成去除最后一页并带有居中页码的文档: {OUTPUT_DOCX}') 